package com.ftdc.app.thread;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierExample {
    public static void main(String[] args) {
        int numberOfThreads = 3;
        CyclicBarrier barrier = new CyclicBarrier(numberOfThreads, () -> {
            System.out.println("All threads have reached the barrier. Let's proceed.");
        });

        for (int i = 0; i < numberOfThreads; i++) {
            new Thread(new Worker3(barrier)).start();
        }
    }
}

class Worker3 implements Runnable {
    private final CyclicBarrier barrier;

    public Worker3(CyclicBarrier barrier) {
        this.barrier = barrier;
    }

    @Override
    public void run() {
        try {
            // 模拟工作
            System.out.println(Thread.currentThread().getName() + " is working.");
            Thread.sleep((long) (Math.random() * 1000));
            System.out.println(Thread.currentThread().getName() + " has reached the barrier.");
            barrier.await(); // 等待其他线程到达屏障
        } catch (InterruptedException | BrokenBarrierException e) {
            e.printStackTrace();
        }
    }
}
